package timer

import (
	"shop/common/log"
	"shop/config"
	"shop/config/constant"
	"shop/dao"
	"shop/entity"
	"shop/service"
	"shop/utils/convertutil"
	"shop/utils/result"
	"time"
)

func StartTimerTask() {
	go startGoodsMenusCacheTimer()
	go timerClearCacheAt24()
	go timePerHour()
}

//  定时从redis里拉取商品信息保存到本地
func startGoodsMenusCacheTimer() {
	for {
		for i := range config.MerchantConfs {
			shopId := config.MerchantConfs[i].ShopId
			service.GoodsMenuListCache[shopId] = service.GetGoodsMenuListFromDB(shopId)
		}
		log.Infof("定时刷新店铺菜单列表信息到本地缓存，len=%d", len(service.GoodsMenuListCache))
		time.Sleep(time.Second * 5)
	}
}

// 凌晨0点的定时任务
func timerClearCacheAt24() {
	for {
		now := time.Now()
		next := time.Date(now.Year(), now.Month(), now.Day()+1, 0, 0, 0, 0, now.Location())
		time.Sleep(time.Until(next))

		// 清理缓存
		log.Infof("清除今日验证码的发送次数记录, count=%d", dao.GetRedisCli().Del(constant.CacheKeyVerifyCodeSendCountMap).Val())
	}
}

func timePerHour() {
	for {
		// 删除超过1小时未付款的订单
		count := dao.GetDB().Table(entity.TableNameOrderInfo).
			Where("order_status=? and create_time<?", constant.OrderStatusNotPay, time.Now().Unix()-3600).
			Delete(nil).RowsAffected
		log.Infof("删除超过1小时未付款的订单, count=%d", count)

		// 自动确认收货超过1天的订单
		orders := make([]*entity.OrderInfo, 0)
		err := dao.GetDB().Table(entity.TableNameOrderInfo).
			Where("order_status=? and create_time<?", constant.OrderStatusWaitTake, time.Now().Unix()-3600*24).Find(&orders).Error
		if err != nil {
			log.Errorf("[自动确认收货] 获取订单列表失败, err: %s", err)
			continue
		}
		for _, order := range orders {
			r := service.ConfirmReceiveAndAddGoodsSoldCount(order.OrderNo, order.UserId)
			if r.Code != result.ErrCodeOk {
				log.Errorf("自动确认收货失败, order:%s, res:%s", convertutil.ToJsonString(order), convertutil.ToJsonString(r))
			} else {
				log.Infof("自动确认收货, orderNo=%s, userId=%d", order.OrderNo, order.UserId)
			}
		}

		time.Sleep(time.Hour)
	}
}
